package com.pl.service.impl;

import com.pl.common.JsonResult;
import com.pl.service.PictureService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author shent
 */
@Service
public class PictureServiceImpl implements PictureService {
    @Value("${file.fileImgUpload}")
    String imgUpload;
    @Value("${file.staticPath}")
    String staticPath;
    @Value("${file.serverLocation}")
    String serverLocation;

    @Override
    public JsonResult savePicture(MultipartFile image) throws Exception {
        String url = null;
        if (image.isEmpty()) {
            return new JsonResult(500, "上传图片不能为空");
        }
        String fileName = image.getOriginalFilename();
        fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + "_" + fileName;
        String path = imgUpload + fileName;
        File imgFile = new File(path);
        if (imgFile.exists()) {
            return new JsonResult(500, "图片已存在");
        }
        if (!imgFile.getParentFile().exists()) {
            if (!imgFile.getParentFile().mkdir()) {
                return new JsonResult(500, "父文件夹创建失败");
            }
        }
        image.transferTo(imgFile);
        url = serverLocation + staticPath + fileName;

        return new JsonResult(url);
    }
}
